package models
import (
	db "hulk-api/databases"
	"fmt"
	"time"
	. "hulk-api/logger"
)
//定义person类型结构


type User struct {
	Account string 		`json:"account"`
	Password string		`json:"password"`
	UserName string		`json:"username"`
	Email string		`json:"email"`
	Department string		`json:"department"`
	Role string			`json:"role"`
	LastLoginTime string	`json:"last_login_time"`

}



//登录接口-用户获取
func (u User) GetUser() ( user User, err error) {
	sql := fmt.Sprintf("SELECT account,password FROM user WHERE account= '%s' and password = '%s'",u.Account,u.Password)
	fmt.Println("Debug sql:" , sql)
	err = db.SqlDB.QueryRow(sql).Scan(
		&user.Account,&user.Password,
	)
	return
}

//系统管理-用户管理
func (u User) GetUsers() ( users []User, err error) {
	users = make([]User,0)
	//sql := fmt.Sprintf(" select account,name,email,department,role,lastLoginTime from user")
	rows, err := db.SqlDB.Query("select account,name,email,department,role,lastLoginTime from user")
	defer rows.Close()

	for rows.Next() {
		var u User
		rows.Scan(&u.Account, &u.UserName, &u.Email,&u.Department,&u.Role,&u.LastLoginTime)
		users = append(users, u)
	}

	if err = rows.Err(); err != nil {
		return
	}
	return
}


//系统管理-用户管理-删除用户
func (u User) DeleteUser() (  err error) {
	fmt.Println("this account is",u.Account)
	_, err = db.SqlDB.Exec("DELETE FROM user WHERE account=?", u.Account)
	return
}
//系统管理-用户管理-新增用户
func (u User) AddUser() (  err error) {
	_, err = db.SqlDB.Exec("insert into user(account,name,email,department,role,password) values (?,?,?,?,?,?)", u.Account,u.UserName,u.Email,u.Department,u.Role,u.Password)
	return
}

//系统管理-用户管理-密码重置
func (u User) ResetPassword() (  err error) {
	fmt.Println("this account is",u.Account)
	fmt.Println("this password is",u.Password)
	_, err = db.SqlDB.Exec("update user set password=? where account = ?",u.Password , u.Account)
	return
}

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


func (u User) UpdateUserLoginDatetime(){
	sql := fmt.Sprintf("update  user set lastLoginTime = '%s' WHERE account= '%s' ",time.Now().Format("2006-01-02 15:04:05"),u.Account)
	fmt.Println("DEBUG update last login time " , sql)
	_,err := db.SqlDB.Exec(sql)
	checkErr(err)
	return
}

func checkErr(err error)  {
	defer Log.Flush()
	if err != nil {
		Log.Error(err.Error())
	}
}

